package com.bxd.baodan.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.bxd.baodan.App;
import com.bxd.baodan.R;
import com.bxd.baodan.adapter.CommonAdapter;
import com.bxd.baodan.adapter.ViewHolder;
import com.bxd.baodan.app.JsonApi;
import com.bxd.baodan.app.LoginInfo;
import com.bxd.baodan.fragment.AreaAction;
import com.bxd.baodan.item.AdviserSearchConditionItem;
import com.bxd.baodan.item.AdviserSearchConditionItem.DataItemX.RegionItem;
import com.bxd.baodan.item.AdviserSearchConditionItem.DataItemX.RegionItem.DataItem;
import com.bxd.baodan.item.RecommendAgentItem.DataItem.AgentBean;
import com.bxd.baodan.util.GlideUtil;
import com.bxd.baodan.util.JSONUtil;
import com.bxd.baodan.util.NetUtil;
import com.bxd.baodan.util.NetUtil.RequestStringListener;
import com.bxd.baodan.util.SpUtil;
import com.bxd.baodan.widget.MyPopupWindow;
import com.tencent.TIMConversationType;
import com.tencent.qcloud.timchat.ui.ChatActivity;
import com.umeng.analytics.MobclickAgent;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


public class FindAdviserActivity extends BaseListActivity<AgentBean> {
    private TextView areaTv;
    private TextView sortTv;
    private TextView pCompany;


    private ListView popListView;
    private MyPopupWindow popMenu;

    private MyPopupWindow areaMenu;

    private CommonAdapter<DataItem> typeAdapter;

    public List<RegionItem> areaList = new ArrayList<>();
    public List<DataItem> sortList = new ArrayList<>();


    String proId, cityId, sortId;
    String companyId = "0";


    @Override
    protected int getActivityLayout() {
        return R.layout.activity_find_adviser;
    }

    @Override
    protected void preDone() {
        setActionBarTitle("顾问列表");

        areaTv = (TextView) findViewById(R.id.tv_area_fdgw);
        sortTv = (TextView) findViewById(R.id.tv_default_fdgw);
        pCompany = (TextView) findViewById(R.id.tv_company_fdgw);


        areaTv.setOnClickListener(this);
        sortTv.setOnClickListener(this);
        pCompany.setOnClickListener(this);

        initPopMenu();

    }


    @Override
    public void setNetUtil() {
        netUtil = new NetUtil(this,
                JsonApi.AGENT_LISTS);
    }


    @Override
    protected Type getTypeToken() {
        return new TypeToken<List<AgentBean>>() {
        }.getType();
    }


    @Override
    public int getItemLayout() {
        return R.layout.find_adviser_item;
    }

    @Override
    public void convert(ViewHolder holder, final AgentBean item) {
        GlideUtil.loadCircle(FindAdviserActivity.this, item.ue_avatar, (ImageView) holder.getView(R.id.image_avtar));
        holder.setText(R.id.name, item.ue_realname);

        String verify = "";
        int level = item.ua_title;
        int verColor = R.color.white;
        int drawableLeft = R.color.transparent;
        switch (level) {
            case 0:
                break;
            case 4:
                verify = "保险管家";
                verColor = R.color.guanja;
                drawableLeft = R.drawable.round_corner_yellow;
                break;
            case 2:
                verify = "保险精英";
                verColor = R.color.jingying;
                drawableLeft = R.drawable.round_corner_blue_jingying;
                break;
            case 1:
                verify = "保险达人";
                verColor = R.color.daren;
                drawableLeft = R.drawable.round_corner_green;
                break;
            case 3:
                verify = "保险专家";
                verColor = R.color.zhuanjia;
                drawableLeft = R.drawable.round_corner_red_zhuanjia;
                break;
            default:
                break;
        }

        holder.getView(R.id.verify_level).setBackground(getResources().getDrawable(drawableLeft));

        holder.setText(R.id.verify_level, verify);
        ((TextView) holder.getView(R.id.verify_level)).setTextColor(getResources().getColor(verColor));

        int chatStatus = item.ue_onlineStatus;
        holder.getView(R.id.chat_status).setBackground(getResources().getDrawable(chatStatus == 0 ? R.drawable.round_corner_gray : R.drawable.round_corner_yellow));
        ((TextView) holder.getView(R.id.chat_status)).setCompoundDrawablesWithIntrinsicBounds(getResources().getDrawable(chatStatus == 0 ? R.drawable.one_by_one_gray : R.drawable.one_by_one), null, null, null);
        ((TextView) holder.getView(R.id.chat_status)).setTextColor(getResources().getColor(chatStatus == 0 ? R.color.gray : R.color.yellow_lab));

        holder.getView(R.id.chat_status).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //顾问一对一点击
                MobclickAgent.onEvent(FindAdviserActivity.this, "");
                if (LoginInfo.getInstance(App.getContext()).isLogin()) {
                    ChatActivity.navToChat(FindAdviserActivity.this, item.u_id + "", TIMConversationType.C2C);
                } else {
                    FindAdviserActivity.this.startActivity(new Intent(FindAdviserActivity.this, LoginActivity.class));
                    ((Activity) FindAdviserActivity.this).overridePendingTransition(R.anim.slide_in_right,
                            R.anim.slide_out_left);
                }
            }
        });


        String str = (Integer.parseInt(item.serviceCount) == 0 ? "" : (",已服务" + item.serviceCount + "投保人"));
        holder.setText(R.id.agent_content, "从业" + item.workTime + "年" + str);
        if (item.agent_mark != null && item.agent_mark.length > 0
                && Arrays.asList(item.agent_mark).contains("6")) {
            holder.getView(R.id.verify_icon).setVisibility(View.VISIBLE);
        } else {
            holder.getView(R.id.verify_icon).setVisibility(View.GONE);
        }

        holder.setText(R.id.tv_company, "机构：" + item.companyname);
        try {
            holder.setText(R.id.tv_distance, "地区：" + item.city);
        } catch (Exception e) {
        }

        holder.getView(R.id.main).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MobclickAgent.onEvent(App.getContext(), "v5_5_1_SY_zgw_zy");
                openActivity(AdviserActivity.class, new String[]{"params"}, new String[]{item.u_id});
            }
        });

    }

    public CommonAdapter<DataItem> getAdapter(List<DataItem> list, final TextView tv) {
        return new CommonAdapter<DataItem>(this, list, R.layout.left_right_item) {
            @Override
            public void convert(final ViewHolder holder, final DataItem item) {


                if (tv.getText().equals(item.name)) {
                    holder.setText(R.id.middle_tv, item.name);
                    ((TextView) holder.getView(R.id.middle_tv)).setTextColor(getResources().getColor(R.color.green_3));
                    holder.setImageResource(R.id.right_iv, R.drawable.p_checked);
                    holder.setImageResource(R.id.left_iv, R.color.transparent);


                } else {
                    holder.setText(R.id.middle_tv, item.name);
                    ((TextView) holder.getView(R.id.middle_tv)).setTextColor(getResources().getColor(R.color.text_black));
                    holder.setImageResource(R.id.right_iv, R.color.transparent);
                    holder.setImageResource(R.id.left_iv, R.color.transparent);
                }
                holder.getView(R.id.l_r_layout).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        tv.setText(item.name);
                        sortId = item.id;

                        popMenu.dismiss();

                        // FIXME: 17/7/25 多次请求,要清参数,防止把标示传进去
                        netUtil.clearParams();

                        netUtil.setParams("sort", sortId);
                        netUtil.setParams("city ", cityId);
                        netUtil.setParams("province ", proId);
                        netUtil.setParams("company ", companyId);

                        autoRefresh();
                    }
                });
            }
        };
    }

    private void initMenuData() {

        typeAdapter = getAdapter(sortList, sortTv);

        NetUtil conditionNet = new NetUtil(this, JsonApi.AGENT_SEARCHCONDITION);
        conditionNet.postRequest("", new RequestStringListener() {
            @Override
            public void onComplete(String result) {
                if (JSONUtil.isSuccess(result)) {
                    SpUtil.getInstance().savaString(JsonApi.AGENT_SEARCHCONDITION, result);
                    loadCondition(result);
                } else {
                    //从缓存中读数据
                    String cache = SpUtil.getInstance().getString(JsonApi.AGENT_SEARCHCONDITION);
                    if (cache != null && !cache.isEmpty()) {
                        loadCondition(cache);
                    }

                }
            }
        });


    }


    /**
     * 筛选条件data
     *
     * @param result
     */
    public void loadCondition(String result) {
        AdviserSearchConditionItem searchConditionItem = new Gson().fromJson(result, AdviserSearchConditionItem.class);
        List<RegionItem> regions = searchConditionItem.data.region;
        List<DataItem> sort = searchConditionItem.data.sort;
        areaList.clear();
        sortList.clear();
        areaList.addAll(regions);
        sortList.addAll(sort);


        sortTv.setText(sortList.get(0).name);
        areaTv.setText(areaList.get(0).data.get(0).name);
        proId = areaList.get(0).id;
        cityId = areaList.get(0).data.get(0).id;
        sortId = sortList.get(0).id;
        companyId = "0";
        initAreaMenuData(areaList);
        typeAdapter.notifyDataSetChanged();


        netUtil.setParams("sort", sortId);
        netUtil.setParams("city ", cityId);
        netUtil.setParams("province ", proId);
        netUtil.setParams("company ", companyId);

        autoRefresh();
    }

    @Override
    public void onClick(View v) {
        Drawable drawable = getResources().getDrawable(R.drawable.p_arrow_down_green);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        switch (v.getId()) {


            case R.id.tv_area_fdgw:
                areaTv.setCompoundDrawables(null, null, drawable, null);
                areaTv.setTextColor(Color.parseColor("#39ac69"));
                areaMenu.showAsDropDown(findViewById(R.id.line));

                break;
            case R.id.tv_default_fdgw:
                sortTv.setCompoundDrawables(null, null, drawable, null);
                sortTv.setTextColor(Color.parseColor("#39ac69"));
                popListView.setAdapter(typeAdapter);
                popMenu.showAsDropDown(findViewById(R.id.line));
                break;
            case R.id.tv_company_fdgw:
                drawable = getResources().getDrawable(R.drawable.p_check_company);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                pCompany.setCompoundDrawables(null, null, drawable, null);
                pCompany.setTextColor(Color.parseColor("#37b059"));
                openActivityForResult(AllCompanyActivity.class, new String[]{"company_name"}, new String[]{pCompany.getText().toString()});
                break;
        }
    }

    // FIXME: 17/7/25 没有初始化
    @Override
    protected String getArrayStr(String json_data) {
        return "list";
    }

    private void initPopMenu() {
        initMenuData();
        View contentView = View.inflate(this, R.layout.popwin_supplier_list,
                null);

        popMenu = new MyPopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        popMenu.setOutsideTouchable(true);
        popMenu.setBackgroundDrawable(new BitmapDrawable());
        popMenu.setFocusable(true);
        popMenu.setAnimationStyle(R.style.popwin_anim_style);
        popMenu.setOnDismissListener(new PopupWindow.OnDismissListener() {
            public void onDismiss() {
                Drawable drawable = getResources().getDrawable(R.drawable.p_arrow_down_gray);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                areaTv.setTextColor(getResources().getColor(R.color.text_black));
                sortTv.setTextColor(getResources().getColor(R.color.text_black));
                areaTv.setCompoundDrawables(null, null, drawable, null);
                sortTv.setCompoundDrawables(null, null, drawable, null);
            }
        });

        popListView = (ListView) contentView
                .findViewById(R.id.popwin_supplier_list_lv);
        contentView.findViewById(R.id.popwin_supplier_list_bottom)
                .setOnClickListener(new View.OnClickListener() {
                    public void onClick(View arg0) {
                        popMenu.dismiss();
                    }
                });


    }


    private void initAreaMenuData(List<RegionItem> list) {

        View contentView = View.inflate(this, R.layout.fragment_area,
                null);

        final AreaAction action = new AreaAction(this, contentView, list);
        action.setData(new AreaAction.AreaCheckListener() {
            @Override
            public void checkedData(String name, String id, String proid) {
                areaTv.setText(name);
                cityId = id;
                proId = proid;
                areaMenu.dismiss();

                netUtil.clearParams();
                netUtil.setParams("sort", sortId);
                netUtil.setParams("city ", cityId);
                netUtil.setParams("province ", proId);
                netUtil.setParams("company", companyId);
                autoRefresh();
            }
        });


        areaMenu = new MyPopupWindow(contentView,
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT);
        areaMenu.setOutsideTouchable(true);
        areaMenu.setBackgroundDrawable(new BitmapDrawable());
        areaMenu.setFocusable(true);
        areaMenu.setAnimationStyle(R.style.popwin_anim_style);
        areaMenu.setOnDismissListener(new PopupWindow.OnDismissListener() {
            public void onDismiss() {
                Drawable drawable = getResources().getDrawable(R.drawable.p_arrow_down_gray);
                drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                areaTv.setTextColor(getResources().getColor(R.color.text_black));
                sortTv.setTextColor(getResources().getColor(R.color.text_black));
                areaTv.setCompoundDrawables(null, null, drawable, null);
                sortTv.setCompoundDrawables(null, null, drawable, null);

                action.clearData();

            }
        });


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Drawable drawable = getResources().getDrawable(R.drawable.p_uncheck_company);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
        pCompany.setCompoundDrawables(null, null, drawable, null);
        pCompany.setTextColor(getResources().getColor(R.color.text_black));
        if (resultCode == 200) {
            pCompany.setText(data.getStringExtra("company_name"));
            companyId = data.getStringExtra("company_id");
            if (companyId == null) {
                companyId = "0";
            }
            netUtil.clearParams();
            netUtil.setParams("sort", sortId);
            netUtil.setParams("city ", cityId);
            netUtil.setParams("province ", proId);
            netUtil.setParams("company", companyId);
            autoRefresh();
        }
    }


}
